/**
 * Created by duanq on 2017/4/8.
 */
import React,{ Component } from 'react';
import axios from 'axios';
import { hashHistory } from 'react-router';
import { Form, Input, Tooltip, Icon, Row, Col, Checkbox, Button ,Alert} from 'antd';
import 'antd/dist/antd.css';
import '../../css/register.css';
const FormItem = Form.Item;

class  Register extends Component{
    constructor(props){
        super(props);
        this.state = { confirmDirty: false,email:'success'};
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
        const form = this.props.form;
        let url = 'register';
        var registerData = `userName=${this.props.form.getFieldValue('userName')}&password=${this.props.form.getFieldValue("password")}&email=${this.props.form.getFieldValue("email")}`;
        axios.post(url,registerData)
            .then(function (response) {
                console.log(response);
                if(response.data == "success"){
                    sessionStorage.setItem("loginFlag",true);
                    const path = `home`;
                    hashHistory.push(path);
                }
            })
            .catch(function (error) {
                console.log(error);
            })
    };
    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    };
    checkPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('Two passwords that you enter is inconsistent!');
        } else {
            callback();
        }
    };
    checkConfirm = (rule, value, callback) => {
        const form = this.props.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], { force: true });
        }
        callback();
    };
    handleEmailBlur = (e) => {
        const form = this.props.form;
        let that = this;
        let url = 'email';
        let emailData = `email=${this.props.form.getFieldValue('email')}`;
        axios.post(url,emailData)
            .then(function (response) {
                that.setState({'email':`${response.data}`});
            })
            .catch(function (error) {
                console.log(error);
            });
    };
    checkEmail = (rule, value, callback) => {
        if (this.state.email=="error") {
            callback("the email already be registered");
        } else{
            callback();
        }
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 14 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 14 },
                sm: { span: 14 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span:14,
                    offset: 6,
                },
            },
        };
        return (
            <div>
                <Row type="flex" justify="center">
                    <Col span={8}>
                        <p className="register-title"> </p>
                        <Form onSubmit={this.handleSubmit}>
                            <FormItem
                                {...formItemLayout}
                                label="E-mail"
                                hasFeedback
                            >
                                {getFieldDecorator('email', {
                                    rules: [{
                                        type: 'email', message: 'The input is not valid E-mail!',
                                    }, {
                                        required: true, message: 'Please input your E-mail!',
                                    },{
                                        validator: this.checkEmail,
                                    }],
                                })(
                                    <Input onBlur={this.handleEmailBlur}/>
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="Password"
                                hasFeedback
                            >
                                {getFieldDecorator('password', {
                                    rules: [{
                                        required: true, message: 'Please input your password!',
                                    }, {
                                        validator: this.checkConfirm,
                                    }],
                                })(
                                    <Input type="password" />
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="Confirm Password"
                                hasFeedback
                            >
                                {getFieldDecorator('confirm', {
                                    rules: [{
                                        required: true, message: 'Please confirm your password!',
                                    }, {
                                        validator: this.checkPassword,
                                    }],
                                })(
                                    <Input type="password" onBlur={this.handleConfirmBlur} />
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                          Username&nbsp;
                                        <Tooltip title="What do you want other to call you?">
                            <Icon type="question-circle-o" />
                          </Tooltip>
                        </span>
                                )}
                                hasFeedback
                            >
                                {getFieldDecorator('userName', {
                                    rules: [{ required: true, message: 'Please input your Username!', whitespace: true }],
                                })(
                                    <Input />
                                )}
                            </FormItem>
                            <FormItem {...tailFormItemLayout} style={{ marginBottom: 8}}>
                                {getFieldDecorator('agreement', {
                                    valuePropName: 'checked',
                                })(
                                    <Checkbox>I have read the <a href="">agreement</a></Checkbox>
                                )}
                            </FormItem>
                            <FormItem {...tailFormItemLayout}>
                                <Button type="primary" htmlType="submit" size="large" className={"register-form-button"}>Register</Button>
                            </FormItem>
                        </Form>
                    </Col>
                </Row>
            </div>
        );
    }
}
export const RegisterForm = Form.create()(Register);